/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ke.me.muhia.spring.masomo.provisioning.xmlrpc;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcCommonsTransport;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;
import org.apache.xmlrpc.client.XmlRpcSunHttpTransportFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Kenneth
 */
public class CustomXmlRpcSunTransportFactory extends XmlRpcSunHttpTransportFactory {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public CustomXmlRpcSunTransportFactory(XmlRpcClient pClient) {
        super(pClient);
    }

//    public XmlRpcTransport getTransport(){
//        return new LoggingTra
//    }
}

class LoggingTransport extends XmlRpcCommonsTransport {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public LoggingTransport(XmlRpcCommonsTransportFactory pFactory) {
        super(pFactory);
    }

    /**
     * Logs the request content in addition to the actual work.
     */
    @Override
    protected void writeRequest(final ReqWriter pWriter) throws XmlRpcException {
        super.writeRequest(pWriter);
        if (logger.isDebugEnabled()) {
            CustomLoggingUtils.logRequest(logger, method.getRequestEntity());

        }
    }

    /**
     * Logs the response from the server, and returns the contents of the
     * response as a ByteArrayInputStream.
     */
    @Override
    protected InputStream getInputStream() throws XmlRpcException {
        InputStream istream = super.getInputStream();
        if (logger.isDebugEnabled()) {
            return new ByteArrayInputStream(CustomLoggingUtils.logResponse(logger, istream).getBytes());
        } else {
            return istream;
        }
    }

}
